import { MyChatConversationResult } from "@/apis/endpoint/model"
import { getMychatChatdetailId, getMychatPreconnect, postMychatReadmsgId } from "@/apis/endpoint/myChat"
import { useEffect, useRef, useState } from "react"
import Taro from "@tarojs/taro"
import { RouteParams } from "../types"

interface SocketEvents {
  open(): any
  message(data: string): any
}

export function useChatDetail(params: RouteParams, events: SocketEvents) {
  const [chatDetail, setChatDetail] = useState<INullable<MyChatConversationResult>>(null)
  const socketTask = useRef<INullable<Taro.SocketTask>>(null)
  useEffect(() => {
    getMychatChatdetailId(Number(params.id)).send()
    .then(detail => {
      setChatDetail(detail)
      if (detail.unreadCount)
        postMychatReadmsgId(Number(params.id)).send()
    })
    .then(() => getMychatPreconnect().send())
    .then(({server}) => Taro.connectSocket({ url: server! }))
    .then(socket => {
      socketTask.current = socket
      socket.onOpen(() => {
        events.open()
        process.env.NODE_ENV !== "production" && console.log("%c已成功连接到socket服务", "color: green; font-size: 24px;")
      })
      socket.onClose(() => {
        process.env.NODE_ENV !== "production" && console.log("%c已断开socket服务连接", "color: pink; font-size: 24px;")
      })
      socket.onError(({errMsg}) => {
        Taro.showModal({
          title: "连接失败",
          content: `会话服务器连接失败: ${errMsg}`,
          showCancel: false
        })
      })
      socket.onMessage(({data}) => {
        if (process.env.NODE_ENV !== "production") {
          console.log("%c接收到socket数据", "color: skyblue; font-size: 24px;")
          console.log(typeof data === "string" ? JSON.parse(data): data)
        }
        events.message(data)
      })
    })
    return () => {
      if (socketTask.current) socketTask.current.close({})
    }
  }, [])
  return {
    chatDetail
  }
}
